﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using FDEE.Model;
using FDEEInterface;
using FDEEPublicFunc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FDEEDrawingModels
{
    public class PlotBarrierPositionByExcelTable
    {
        static string _dwgPath = "";//构造物
        static string _blcName = "MA";
 

        #region Excel2CAD
        public static void DrawingExcel2CADTable(Database db, System.Data.DataTable dt0, string dwgPath,
         string pierName, ref int pageCount, int pageNo = 0, int scale = 1, string title = "MAINLINE", string tkPath = "")
        {
            if (dt0 == null || dt0.Rows.Count == 0)
            {
                throw new Exception("数据异常");
            }
           
            //System.Data.DataTable dt = dv0.ToTable(true, new string[] { "Pier", "Position", "Left", "Right", "B1", "B2" });
            System.Data.DataTable dt = dt0.Copy();
            dt.Columns[0].ColumnName = "Pier";
            dt.Columns[1].ColumnName = "Position";
            dt.Columns[2].ColumnName = "Left";
            dt.Columns[3].ColumnName = "Right";
            dt.Columns[4].ColumnName = "B1";
            dt.Columns[5].ColumnName = "B2";

            _dwgPath = dwgPath;

            Extents2d ext = new Extents2d(Point2d.Origin, Point2d.Origin);
            Point2d CT = Point2d.Origin.Convert2D(0, -297 * pageNo);
           

            #region 分页处理
            DataView dv0 = dt.DefaultView;
            System.Data.DataTable dtP= dv0.ToTable(true, "Pier");
            List<Tuple<string, System.Data.DataRow[],int>> tuples = new List<Tuple<string, DataRow[],int>>(); ;
            Tuple<string, System.Data.DataRow[],int> tuple;
            for (int i =0 ; i < dtP.Rows.Count; i++)
            {
                System.Data.DataRow[] drs = dt.Select("Pier='" + dtP.Rows[i]["Pier"].ToString() + "'");
                tuple=new Tuple<string, DataRow[],int>(dtP.Rows[i]["Pier"].ToString(), drs, drs.Length);
                tuples.Add(tuple);
            }

            List<Tuple<List<Tuple<string, System.Data.DataRow[], int>>,int,bool>> lstTu=new List<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>();
            Tuple<List<Tuple<string, System.Data.DataRow[], int>>, int, bool> tu;
            int tbC1 = 0;
            int tbC2 = 0;
            int rowCount = 0;
            List<Tuple<string, System.Data.DataRow[], int>> tu0=new List<Tuple<string, DataRow[], int>>();
            for (int i=0;i< tuples.Count; i++)
            {
                if (pierName.Contains(tuples[i].Item1))
                {
                    if (rowCount > 0)
                    {
                        tu = new Tuple<List<Tuple<string, DataRow[], int>>, int, bool>(tu0, rowCount, false);
                        lstTu.Add(tu);
                        tbC1++;
                    }
                    tu0 = new List<Tuple<string, DataRow[], int>>();
                    tu0.Add(tuples[i]);
                    tu = new Tuple<List<Tuple<string, DataRow[], int>>, int, bool>(tu0, tuples[i].Item3, true);
                    lstTu.Add(tu);
                    tbC2++;
                    rowCount =0;
                    tu0 = new List<Tuple<string, DataRow[], int>>();                 
                }
                else
                {
                    rowCount += tuples[i].Item3;
         
                    if (i == tuples.Count - 1)
                    {
                        if (rowCount <= 24)
                        {
                            tu0.Add(tuples[i]);
                            tu = new Tuple<List<Tuple<string, DataRow[], int>>, int, bool>(tu0, rowCount, false);
                            lstTu.Add(tu);
                        }
                        else
                        {
                            tu = new Tuple<List<Tuple<string, DataRow[], int>>, int, bool>(tu0, rowCount - tuples[i].Item3, false);
                            lstTu.Add(tu);

                            tu0 = new List<Tuple<string, DataRow[], int>>();
                            tu0.Add(tuples[i]);
                            rowCount = tuples[i].Item3;
                            tu = new Tuple<List<Tuple<string, DataRow[], int>>, int, bool>(tu0, rowCount, false);
                            lstTu.Add(tu);
                        }
                       
                    }
                    else
                    {
                        if (rowCount <= 24)
                        {
                            tu0.Add(tuples[i]);

                        }
                        else
                        {
                            tu = new Tuple<List<Tuple<string, DataRow[], int>>, int, bool>(tu0, rowCount - tuples[i].Item3, false);
                            lstTu.Add(tu);
                            rowCount = tuples[i].Item3;
                            tu0 = new List<Tuple<string, DataRow[], int>>();
                            tu0.Add(tuples[i]);
                            tbC1++;
                        }
                    }
                }
            }
            pageCount = 0;
            #endregion

            #region 绘制表格
          
            int stPnum = 0;
            Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>> tp;
            List<Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>> pLst = new List<Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>>();
            for (int i=0;i< lstTu.Count;i++)
            {
                Tuple<List<Tuple<string, DataRow[], int>>, int, bool> tuItem = lstTu[i];
           
                if (tuItem.Item3)
                {
                    if (stPnum % 2 == 1)
                    {
                        tp = new Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>(lstTu[i-1], null);
                        pLst.Add(tp);
                    }
                    tp = new Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>( lstTu[i],null);
                    pLst.Add(tp);
                    stPnum = 0;
                }
                else
                {
                    stPnum++;
              
                    if (i == lstTu.Count - 1)
                    {
                        if (stPnum % 2 == 0)
                        {
                            tp = new Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>(lstTu[i - 1], lstTu[i]);
                            pLst.Add(tp);
                        }
                        else
                        {
                            tp = new Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>(lstTu[i], null);
                            pLst.Add(tp);
                        }
                    }
                    else
                    {
                        if (stPnum % 2 == 0)
                        {
                            tp = new Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>>(lstTu[i - 1], lstTu[i]);
                            pLst.Add(tp);
                        }
                    }
                }
              
            }
            Table lasTb = new Table();
            Point2d M1 = CT.Convert2D();
            for (int i = 0; i < pLst.Count; i++)
            {
                Tuple<Tuple<List<Tuple<string, DataRow[], int>>, int, bool>, Tuple<List<Tuple<string, DataRow[], int>>, int, bool>> tPage = pLst[i];
                Point2d insertPoint = M1.Convert2D(420 * i);
                ext = new Extents2d(insertPoint, insertPoint);
                //lasTb = DrawTable(db, ref ext, M1.Convert3D(), Extensions.curFont, scale, List[i], dt, pierName, i, title);
                if(tPage.Item2!=null)
                {
                    lasTb = DrawTable(db, ref ext, insertPoint.Convert3D(), Extensions.curFont, scale, tPage.Item1.Item1, tPage.Item1.Item2, title);
                    Point3d insertPoint2 = insertPoint.Convert3D(lasTb.Width+30);
                    lasTb = DrawTable(db, ref ext, insertPoint2, Extensions.curFont, scale, tPage.Item2.Item1, tPage.Item2.Item2, title);
                }
                else
                {
                    lasTb = DrawTable(db, ref ext, insertPoint.Convert3D(), Extensions.curFont, scale, tPage.Item1.Item1, tPage.Item1.Item2,   title);
                }
                string Contents = "Notes:\\P" +
        "1.Unless otherwise specifed,all dimension in this drawing are in m. \\P"+
         "2.Concrete cover shall be 0.04m for barrier \\P"+
         "3.L' is the length of precast T-gider. \\P";
                TextPloter.PrintMultiText(db, ref ext, insertPoint.Convert3D(ext.W()-100, -lasTb.Height-5), Contents, 1, 2.5, 100);

                Common.CreateLayoutNew(db, "护栏参数表", ext, scale, 1, i, 0, false, tkPath);
            }
            #endregion
        }


        public static Table DrawTable(Database db, ref Extents2d ext, Point3d startPoint,
   string txtStyle, double scale,  List<Tuple<string, DataRow[], int>> tbValue, int rowCount, string title = "MAINLINE")
        {
            //表格表头
            List<string> headName = new List<string>();
            headName.Add("No.of Pier");
            headName.Add("Position(m)");
            headName.Add("Length of girder on the left side");
            headName.Add("Length of girder on the right side");
            headName.Add("B1(m)");
            headName.Add("B2(m)");

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable blockTbl = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord modelSpace = tr.GetObject(blockTbl[BlockTableRecord.ModelSpace],
                    OpenMode.ForWrite) as BlockTableRecord;

                ObjectId id;
                TextStyleTable st = tr.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
                id = st[txtStyle];
                //System.Data.DataRow[] rows=dt.Select()
                startPoint = startPoint.Convert3D();
                Table tb = new Table();
                int colNum = headName.Count;
                tb.SetSize(rowCount+3, colNum);       // 设置几行几列
                tb.Position = startPoint;
                tb.GenerateLayout();
                #region 第一页
                #region 第一行 标题

                tb.Cells[0, 0].TextString = "POSITION INFORMATION OF BARRIER";
                tb.Cells[0, 0].Contents[0].TextHeight = 2.5 * scale;
                tb.Cells[0, 0].Alignment = CellAlignment.MiddleCenter;
                tb.Cells[0, 0].Contents[0].Rotation = 0;
                //tb.Cells[0, 0].Borders.Horizontal.Margin = 1 * scale;
                tb.Cells[0, 0].Contents[0].TextStyleId = id;
                #endregion
                tb.Rows[0].Height = 6.5* scale;

                #region 第二行 表格标题
                for (int i = 0; i < colNum; ++i)
                {
                    tb.Cells[1, i].TextString = headName[i]; //获取i行j列数据
                    tb.Cells[1, i].Contents[0].TextHeight = 2.5 * scale;
                    tb.Cells[1, i].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[1, i].Contents[0].Rotation = 0;
                    tb.Cells[1, i].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[1, i].Contents[0].TextStyleId = id;
                    if (i < 2 || i > 3)
                    {
                        tb.MergeCells(CellRange.Create(tb, 1, i, 2, i));
                    }
                    if (i == 2)
                    {
                        tb.Cells[2, 2].TextString = "L'"; //获取i行j列数据
                        tb.Cells[2, 2].Contents[0].TextHeight = 2.5 * scale;
                        tb.Cells[2, 2].Alignment = CellAlignment.MiddleCenter;
                        tb.Cells[2, 2].Contents[0].Rotation = 0;
                        tb.Cells[2, 2].Borders.Horizontal.Margin = 1 * scale;
                        tb.Cells[2, 2].Contents[0].TextStyleId = id;
                        tb.MergeCells(CellRange.Create(tb, 2, 2, 2, 3));
                    }
                }
                #endregion

                tb.Rows[1].Height = 6.5 * scale;
                tb.Rows[2].Height = 6.5 * scale;

                #region 设置表格值
                int row = 3;
                if (tbValue.Count > 0)
                {
                    for (int m = 0; m < tbValue.Count; m++)
                    {
                        Tuple<string, DataRow[], int> tu = tbValue[m];
                        try
                        {
                            DataRow dr = tu.Item2[0];
                            int n = 0;
                            tb.Cells[row, n].TextString = title + "\\P" + dr["Pier"].ToString(); //获取i行j列数据
                            tb.Cells[row, n].Contents[0].TextHeight = 2 * scale;
                            tb.Cells[row, n].Alignment = CellAlignment.MiddleCenter;
                            tb.Cells[row, n].Borders.Horizontal.Margin = 1 * scale;
                            tb.Cells[row, n].Contents[0].TextStyleId = id;
                            tb.MergeCells(CellRange.Create(tb, row, n, row-1 + tu.Item3, n));

                             n = 2;
                            tb.Cells[row, n].TextString = dr["Left"].ToString(); //获取i行j列数据
                            tb.Cells[row, n].Contents[0].TextHeight = 2 * scale;
                            tb.Cells[row, n].Alignment = CellAlignment.MiddleCenter;
                            tb.Cells[row, n].Borders.Horizontal.Margin = 1 * scale;
                            tb.Cells[row, n].Contents[0].TextStyleId = id;
                            tb.MergeCells(CellRange.Create(tb, row, n, row-1 + tu.Item3, n));

                            n = 3;
                            tb.Cells[row, n].TextString = dr["Right"].ToString(); //获取i行j列数据
                            tb.Cells[row, n].Contents[0].TextHeight = 2 * scale;
                            tb.Cells[row, n].Alignment = CellAlignment.MiddleCenter;
                            tb.Cells[row, n].Borders.Horizontal.Margin = 1 * scale;
                            tb.Cells[row, n].Contents[0].TextStyleId = id;
                            tb.MergeCells(CellRange.Create(tb, row, n, row-1 + tu.Item3, n));

                            //设置值
                            for (int i = 0; i < tu.Item2.Length; i++)
                            {
                                dr = tu.Item2[i];
                                n = 1;
                                tb.Cells[row, n].TextString = dr["Position"].ToString(); //获取i行j列数据
                                tb.Cells[row, n].Contents[0].TextHeight = 2 * scale;
                                tb.Cells[row, n].Alignment = CellAlignment.MiddleCenter;
                                tb.Cells[row, n].Borders.Horizontal.Margin = 1 * scale;
                                tb.Cells[row, n].Contents[0].TextStyleId = id;

                                n = 4;
                                string value = "";
                                try
                                {
                                    value = double.Parse(dr["B1"].ToString()).ToString("0.000");
                                }
                                catch
                                {
                                    value = dr["B1"].ToString();
                                }
                                tb.Cells[row, n].TextString = value; //获取i行j列数据
                                tb.Cells[row, n].Contents[0].TextHeight = 2 * scale;
                                tb.Cells[row, n].Alignment = CellAlignment.MiddleCenter;
                                tb.Cells[row, n].Borders.Horizontal.Margin = 1 * scale;
                                tb.Cells[row, n].Contents[0].TextStyleId = id;

                                n = 5;
                                value = "";
                                try
                                {
                                    value = double.Parse(dr["B2"].ToString()).ToString("0.000");
                                }
                                catch
                                {
                                    value = dr["B2"].ToString();
                                }
                                tb.Cells[row, n].TextString = value; //获取i行j列数据
                                tb.Cells[row, n].Contents[0].TextHeight = 2 * scale;
                                tb.Cells[row, n].Alignment = CellAlignment.MiddleCenter;
                                tb.Cells[row, n].Borders.Horizontal.Margin = 1 * scale;
                                tb.Cells[row, n].Contents[0].TextStyleId = id;
                                row++;
                            }
                        }
                        catch(Exception ex)
                        {

                        }
                    }
                }
                #endregion

                #region 表格添加数据

                #endregion

                #region 设置列宽
                // 设置列宽
                for (int i = 0; i < colNum; ++i)
                {
                    if (i == 0)
                        tb.Columns[i].Width = 6 * 3 * scale;
                    else if (i == 1)
                        tb.Columns[i].Width = 6 * 3 * scale;
                    else if (i == 2|| i == 3)
                        tb.Columns[i].Width = 45 * scale;
                    else 
                        tb.Columns[i].Width = 20 * scale;
                }
                for (int i = 3;i < rowCount + 3;i++)
                {
                    tb.Rows[i].Height = 6 * scale;
                }
                #endregion



                tb.Layer = "细线";
                tb.LineWeight = LineWeight.LineWeight013;
                tb.ColorIndex = 4;
                modelSpace.AppendEntity(tb);
                tr.AddNewlyCreatedDBObject(tb, true);
                ext = ext.Add(new Extents2d(tb.Bounds.Value.MinPoint.Convert2D(), tb.Bounds.Value.MaxPoint.Convert2D()));

                #region  边框粗线设置
                List<Point2d> pList = new List<Point2d>();
                Point2d pt1 = startPoint.Convert2D();
                pList.Add(pt1);
                Point2d pt2 = pt1.Convert2D(0, -tb.Height);
                pList.Add(pt2);
                Point2d pt3 = pt1.Convert2D(tb.Width, -tb.Height);
                pList.Add(pt3);
                Point2d pt4 = pt1.Convert2D(tb.Width, 0);
                pList.Add(pt4);
                PolylinePloter.AddPolylineByList(db, ref ext, pList, "粗线", 2);
                #endregion

                #endregion

                tr.Commit();
                return tb;
            }
        }

        #endregion 

    }
}
